﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CoreDB.Extensions
{
    public static class CollectionExtension
    {
        /// <summary>
        /// 得到集合中指定索引的下一个索引，如果是最后一个索引则返回0
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public static int NextIndex<T>(this IList<T> source, int index)
        {
            return (index + 1) % source.Count;
        }
        public static int NextIndex<T>(this IList<T> source, T value)
        {
            return source.NextIndex(source.IndexOf(value));
        }
        /// <summary>
        /// 得到集合中指定索引的上一个索引，如果是第一个索引则返回末尾索引
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public static int PreviousIndex<T>(this IList<T> source, int index)
        {
            return (index + source.Count - 1) % source.Count;
        }
        public static int PreviousIndex<T>(this IList<T> source, T value)
        {
            return source.PreviousIndex(source.IndexOf(value));
        }
        public static T Next<T>(this IList<T> source, T value)
        {
            return source[source.NextIndex(value)];
        }
        public static T Previous<T>(this IList<T> source, T value)
        {
            return source[source.PreviousIndex(value)];
        }
        /// <summary>
        /// 从集合当前指定索引位置向前遍历，直到刚好遍历完集合所有元素
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="index"></param>
        /// <param name="action"></param>
        public static void Forward<T>(this IList<T> source, int index, Func<T, int, bool> action)
        {
            var currentIndex = index;
            bool result = true;
            do
            {
                result = action.Invoke(source[currentIndex], currentIndex);
                currentIndex = source.NextIndex(currentIndex);
            }
            while (currentIndex != index && result);
        }
        /// <summary>
        /// 从集合当前指定索引位置向后遍历，直到刚好遍历完集合所有元素
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="index"></param>
        /// <param name="action"></param>
        public static void Backward<T>(this IList<T> source, int index, Func<T, int, bool> action)
        {
            var currentIndex = index;
            bool result = true;
            do
            {
                result = action.Invoke(source[currentIndex], currentIndex);
                currentIndex = source.PreviousIndex(currentIndex);
            }
            while (currentIndex != index && result);
        }
    }
}
